package com.mmall.service.impl;

import com.mmall.common.Const;
import com.mmall.common.ServiceResponse;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.util.MD5Util;
import com.mmall.util.RedisShardedPoolUtil;
import net.sf.jsqlparser.expression.operators.arithmetic.Concat;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public ServiceResponse<User> login(String username, String password) {
        int resultCount = userMapper.checkUsername(username);
        if (resultCount == 0){
            return ServiceResponse.createByErrorMessage("用户名不存在");
        }
        //密码登录MD5验证
        String md5Password = MD5Util.MD5EncodeUtf8(password);
        User user = userMapper.selectLogin(username,md5Password);
        if (user == null){
            return ServiceResponse.createByErrorMessage("密码错误");
        }
        user.setPassword(StringUtils.EMPTY); //数据返回到前端，密码要为空
        return ServiceResponse.createBySuccess("登陆成功", user);
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public ServiceResponse<String> register(User user){
        ServiceResponse validResponse = this.checkValid(user.getUsername(),Const.USERNAME);
        if (!validResponse.isSuccess()){
            return validResponse;
        }

        validResponse = this.checkValid(user.getEmail(),Const.EMAIL);
        if (!validResponse.isSuccess()){
            return validResponse;
        }

        user.setRole(Const.Role.ROLE_CUSTOMER);
        //MD5加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));

        int resultCount = userMapper.insert(user);
        if (resultCount == 0){
            return ServiceResponse.createByErrorMessage("注册失败");
        }

        return  ServiceResponse.createBySuccessMessage("注册成功");
    }

    /**
     * 效验用户名，邮箱是否存在
     * @param string
     * @param type
     * @return
     */
    public ServiceResponse<String> checkValid(String string, String type){
        if (StringUtils.isNotBlank(type)){
            //效验用户名是否存在
            if (Const.USERNAME.equals(type)){
                int resultCount = userMapper.checkUsername(string);
                if (resultCount > 0){
                    return ServiceResponse.createByErrorMessage("用户名已存在");
                }
            }
            //效验email是否存在
            if (Const.EMAIL.equals(type)){
                int resultCount = userMapper.checkEmail(type);
                if (resultCount > 0){
                    return ServiceResponse.createByErrorMessage("email已存在");
                }
            }

        }else {
            return ServiceResponse.createByErrorMessage("参数错误");
        }
        return ServiceResponse.createBySuccessMessage("效验成功");
    }

    /**
     * 获取找回问题
     * @param username
     * @return
     */
    public ServiceResponse selectQuestion(String username){
        ServiceResponse validResponse = this.checkValid(username,Const.USERNAME);
        if (validResponse.isSuccess()){
            //验证用户名，邮箱不存在，即用户不存在
            return ServiceResponse.createByErrorMessage("用户不存在");
        }
        String question = userMapper.selectQuestionByUsername(username);
        if (StringUtils.isNotBlank(question)){
            return ServiceResponse.createBySuccess(question);
        }
        return ServiceResponse.createByErrorMessage("找回密码的问题是空的！");
    }

    /**
     * 效验问题答案
     * @param username
     * @param question
     * @param answer
     * @return
     */
    public ServiceResponse<String> checkAnswer(String username, String question, String answer){
        int resultCount = userMapper.checkAnswer(username, question, answer);
        if (resultCount > 0){
            String forgetToken = UUID.randomUUID().toString();
            RedisShardedPoolUtil.setEx(Const.TOKEN_PREFIX+username, forgetToken, 60*60*12);
            return ServiceResponse.createBySuccess(forgetToken);
        }
        return  ServiceResponse.createByErrorMessage("答案错误");
    }

    /**
     * 找回密码
     * @param username
     * @param passwordNew
     * @param forgetToken
     * @return
     */
    public ServiceResponse<String> forgetResetPassword(String username, String passwordNew, String forgetToken){
        if (StringUtils.isBlank(forgetToken)){
            return ServiceResponse.createByErrorMessage("参数错误，token需要传递");
        }
        ServiceResponse validResponse = this.checkValid(username,Const.USERNAME);
        if (validResponse.isSuccess()){
            //用户不存在
            return ServiceResponse.createByErrorMessage("用户不存在");
        }

        String token = RedisShardedPoolUtil.get(Const.TOKEN_PREFIX+username);
        if (StringUtils.isBlank(token)){
            return ServiceResponse.createByErrorMessage("token无效");
        }
        if (StringUtils.equals(forgetToken,token)){
            String md5Password = MD5Util.MD5EncodeUtf8(passwordNew);
            int rowCount = userMapper.updatePasswordByUsername(username,md5Password);
            if (rowCount > 0){
                return ServiceResponse.createBySuccessMessage("密码修改成功");
            }
        }else {
            return ServiceResponse.createByErrorMessage("token错误，请重新获取重置密码的token");
        }
        return ServiceResponse.createByErrorMessage("密码修改失败");
    }

    /**
     * 更新密码
     * @param passwordOld
     * @param passwordNew
     * @param user
     * @return
     */
    public ServiceResponse<String> resetPassword(String passwordOld, String passwordNew, User user){
        //防止横向越权，要效验一下这个用户的旧密码，指定这个用户，如果不指定，则count（1）结果是大于0的
        int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld),user.getId());
        if (resultCount == 0){
            return ServiceResponse.createByErrorMessage("旧密码错误");
        }

        user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if (updateCount > 0){
            return ServiceResponse.createBySuccessMessage("密码更新成功");
        }
        return ServiceResponse.createByErrorMessage("密码更新失败");
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    public ServiceResponse<User> updateInformation(User user) {
        //username是不能被更新的
        //email也要进行一个校验，email是否存在，已存在的email不可再用
        int resultCount = userMapper.checkEmailByUserId(user.getEmail(),user.getId());
        if (resultCount > 0){
            return ServiceResponse.createByErrorMessage("邮箱已被使用，请更换邮箱地址");
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());

        int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);
        if (updateCount > 0){
            return ServiceResponse.createBySuccess("个人信息更新成功", updateUser);
        }
        return ServiceResponse.createByErrorMessage("个人信息更新失败");
    }


    /**
     * 获取用户信息
     * @param userId
     * @return
     */
    public ServiceResponse<User> getInformation(Integer userId){
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null){
            return  ServiceResponse.createByErrorMessage("找不到此用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServiceResponse.createBySuccess(user);
    }


    //管理后台模块

    /**
     * 效验是否为管理员
     * @param user
     * @return
     */
    public ServiceResponse checkAdminRole(User user){
        if (user != null && user.getRole().intValue() == Const.Role.ROLE_ADMIN){
            return ServiceResponse.createBySuccess();
        }
        return ServiceResponse.createByError();
    }
}
